package com.n5x.controller.admin.goods;

import com.github.pagehelper.PageHelper;
import com.n5x.common.base.JsonModel;
import com.n5x.common.base.ResponseCode;
import com.n5x.common.system.Base64;
import com.n5x.controller.BaseController;
import com.n5x.model.goods.*;
import com.n5x.service.IGoodsService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * 商品接口Controller
 * 需要后台管理员token
 */
@Controller("adminGoods")
@RequestMapping("admin/goods")
public class GoodsController extends BaseController {


    @InitBinder("goodsType")
    public void initBinderGoodsType(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("goodsType.");
    }

    @InitBinder("goodsInfo")
    public void initBinderGoodsInfo(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("goodsInfo.");
    }

    @Autowired
    IGoodsService iGoodsService;

    //******************************************商品信息(GoodsInfo)*******************************************/

    @RequestMapping(value = "/list", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public JsonModel goodsInfoList(String token, @RequestParam(value = "id", required = false) String id, @RequestParam(value = "name", required = false) String name, @RequestParam(value = "isSale", required = false) Integer isSale, @RequestParam(value = "group", required = false) Integer group, @RequestParam(value = "type", required = false) String type, @RequestParam(value = "typeName", required = false) String typeName, @RequestParam(value = "pageNum", required = false) Integer pageNum, @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        logger.info("[后台查询商品列表]id:{},name:{},isSale:{},group:{},type:{},pageNum:{},pageSize:{}", new Object[]{id, name, isSale, group, type, pageNum, pageSize});
        try {
            GoodsInfoExample.Criteria criteria = new GoodsInfoExample().createCriteria();
            if (StringUtils.isNotBlank(id)) {
                criteria.andIdEqualTo(id);
            }
            if (StringUtils.isNotBlank(name)) {
                criteria.andNameLike("%" + name + "%");
            }
            if (isSale != null) {
                if (isSale > 0) {
                    criteria.andPreferentialPriceNotEqualTo(new BigDecimal(0));
                } else {
                    criteria.andPreferentialPriceEqualTo(new BigDecimal(0));
                }
            }
            GoodsGroup.GoodsTypeGroupName goodsTypeGroupName = GoodsGroup.GoodsTypeGroupName.getGoodsTypeGroupName(group);
            GoodsGroupExample.Criteria goodsGroupCriteria = null;
            if (goodsTypeGroupName != null) {
                goodsGroupCriteria = new GoodsGroupExample().createCriteria();
                goodsGroupCriteria.andNameEqualTo(goodsTypeGroupName.name());
            }
            GoodsTypeExample.Criteria goodsTypeCriteria = null;
            if (StringUtils.isNotBlank(type)) {
                goodsTypeCriteria = new GoodsTypeExample().createCriteria();
                goodsTypeCriteria.andIdEqualTo(type);
            }
            if (StringUtils.isNotBlank(typeName)) {
                if (goodsGroupCriteria == null) {
                    goodsTypeCriteria = new GoodsTypeExample().createCriteria();
                }
                goodsTypeCriteria.andNameLike("%" + typeName + "%");
            }
            if (pageNum != null && pageSize != null) {
                PageHelper.startPage(pageNum, pageSize);
            }
            List<GoodsInfo> list = iGoodsService.findGoodsInfo(criteria, goodsGroupCriteria, goodsTypeCriteria);
            if (CollectionUtils.isEmpty(list)) {
                return getResultError(ResponseCode.Common_DataNotFound, "商品列表为空");
            }
            return getResult(list);
        } catch (Exception e) {
            e.printStackTrace();
            return getResultError(ResponseCode.Common_Error, e.toString());
        }
    }

    @RequestMapping(value = "/info", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public JsonModel goodsInfo(String token, @RequestParam(value = "id", required = false) String id) {
        logger.info("[后台查询商品信息]id:{}", id);
        try {
            if (StringUtils.isBlank(id)) {
                return getResultError(ResponseCode.Common_ParamError, "商品ID不能为空");
            }
            GoodsInfo goodsInfo = iGoodsService.findGoodsInfo(id);
            if (goodsInfo == null || goodsInfo.getDisable().booleanValue() == true) {
                return getResultError(ResponseCode.Common_DataNotFound, "商品信息为空");
            }
            return getResult(goodsInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return getResultError(ResponseCode.Common_Error, e.toString());
        }
    }

    @RequestMapping(value = "/save", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public JsonModel goodsInfoSave(String token, @ModelAttribute GoodsInfo goodsInfo, @RequestParam(value = "goodsTypeIds", required = false) String[] goodsTypeIds, @RequestParam(value = "goodsGroups", required = false) Integer[] goodsGroups) {
        logger.info("[保存或更新商品信息]GoodsInfo:{},GoodsType:{},GroupNames:{}", goodsInfo, ArrayUtils.isEmpty(goodsTypeIds) ? "" : Arrays.toString(goodsTypeIds), ArrayUtils.isEmpty(goodsGroups) ? "" : Arrays.toString(goodsGroups));
        try {
            if (goodsInfo == null || StringUtils.isBlank(goodsInfo.getName())) {
                return getResultError(ResponseCode.Common_ParamError, "商品信息参数错误");
            }
            if (StringUtils.isNoneBlank(goodsInfo.getPicture())) {
                String deCodeParam = Base64.decode(goodsInfo.getPicture(), "utf-8");
                goodsInfo.setPicture(deCodeParam);
            }
            String content = goodsInfo.getContent();
            if (StringUtils.isNoneBlank(content)) {
                content = content.replaceAll("_a", "\\+");
                content = content.replaceAll("_b", "/");
                content = content.replaceAll("_c", "=");
                goodsInfo.setContent(content);
            }
            String sContent = goodsInfo.getsContent();
            if (StringUtils.isNoneBlank(sContent)) {
                sContent = sContent.replaceAll("_a", "\\+");
                sContent = sContent.replaceAll("_b", "/");
                sContent = sContent.replaceAll("_c", "=");
                goodsInfo.setsContent(sContent);
            }
            Enum<GoodsGroup.GoodsTypeGroupName>[] groupNames = null;
            if (ArrayUtils.isNotEmpty(goodsGroups)) {
                groupNames = new Enum[goodsGroups.length];
                for (int i = 0; i < goodsGroups.length; i++) {
                    groupNames[i] = GoodsGroup.GoodsTypeGroupName.getGoodsTypeGroupName(i);
                }
            }
            goodsInfo = iGoodsService.saveGoodsInfo(goodsInfo, groupNames, goodsTypeIds);
            return getResult(goodsInfo.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return getResultError(ResponseCode.Common_Error, e.toString());
        }
    }

    @RequestMapping(value = "/del", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public JsonModel goodsInfoDel(String token, @RequestParam(value = "id", required = false) String id) {
        try {
            logger.info("[后台删除商品信息]id:{}", new Object[]{id});
            if (StringUtils.isBlank(id)) {
                return getResultError(ResponseCode.Common_ParamError, "商品信息ID不能为空");
            }
            GoodsInfo goodsInfo = iGoodsService.findGoodsInfo(id);
            if (goodsInfo == null) {
                return getResultError(ResponseCode.Common_DataNotFound, "商品信息为空");
            }
            goodsInfo.setDisable(Boolean.TRUE);
            goodsInfo = iGoodsService.saveGoodsInfo(goodsInfo, null, null);
            return getResult(goodsInfo.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return getResultError(ResponseCode.Common_Error, e.toString());
        }
    }

    //******************************************商品类型(GoodsType)*******************************************/

    /**
     * 查询商品类型列表
     *
     * @param token 用户Token
     * @param name  商品类型名称
     * @return JsonModel
     */
    @RequestMapping(value = "/type/list", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public JsonModel goodsTypeList(String token, @RequestParam(value = "name", required = false) String name) {
        try {
            logger.info("[后台查询商品类型列表]name:{}", new Object[]{name});
            GoodsTypeExample.Criteria goodsCriteria = new GoodsTypeExample().createCriteria();
            if (StringUtils.isNotBlank(name)) {
                goodsCriteria.andNameLike("%" + name + "%");
            }
            goodsCriteria.andDisableEqualTo(Boolean.FALSE);
            List<GoodsType> list = iGoodsService.findGoodTypes(goodsCriteria);
            if (CollectionUtils.isEmpty(list)) {
                return getResultError(ResponseCode.Common_DataNotFound, "商品类型列表为空");
            }
            return getResult(list);
        } catch (Exception e) {
            e.printStackTrace();
            return getResultError(ResponseCode.Common_Error, e.toString());
        }
    }

    /**
     * 查看商品类型详细页面
     *
     * @param token 用户token
     * @param id    ID
     * @return JsonModel
     */
    @RequestMapping(value = "/type/info", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public JsonModel goodsTypeInfo(String token, @RequestParam(value = "id", required = false) String id) {
        try {
            logger.info("[后台查询商品类型]id:{}", new Object[]{id});
            if (StringUtils.isBlank(id)) {
                return getResultError(ResponseCode.Common_ParamError, "商品类型ID不能为空");
            }
            GoodsType goodsType = iGoodsService.findGoodTypes(id);
            if (goodsType == null || goodsType.getDisable().booleanValue() == true) {
                return getResultError(ResponseCode.Common_DataNotFound, "商品类型为空");
            }
            return getResult(goodsType);
        } catch (Exception e) {
            e.printStackTrace();
            return getResultError(ResponseCode.Common_Error, e.toString());
        }
    }

    /**
     * 保存商品类型
     *
     * @param token     用户token
     * @param goodsType 商品类型对象
     * @return JsonModel
     */
    @RequestMapping(value = "/type/save", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public JsonModel goodsTypeSave(String token, @ModelAttribute GoodsType goodsType) {
        try {
            logger.info("[后台保存商品类型]goodsType:{}", new Object[]{goodsType});
            if (goodsType == null || StringUtils.isBlank(goodsType.getName())) {
                return getResultError(ResponseCode.Common_ParamError, "商品类型信息不能为空");
            }
            goodsType = iGoodsService.saveGoodsType(goodsType);
            return getResult(goodsType.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return getResultError(ResponseCode.Common_Error, e.toString());
        }
    }

    /**
     * 逻辑删除商品类型
     *
     * @param token 用户token
     * @param id    ID
     * @return JsonModel
     */
    @RequestMapping(value = "/type/del", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public JsonModel goodsTypeDel(String token, @RequestParam(value = "id", required = false) String id) {
        try {
            logger.info("[后台删除商品类型]id:{}", new Object[]{id});
            if (StringUtils.isBlank(id)) {
                return getResultError(ResponseCode.Common_ParamError, "商品类型ID不能为空");
            }
            GoodsType goodsType = iGoodsService.findGoodTypes(id);
            if (goodsType == null) {
                return getResultError(ResponseCode.Common_DataNotFound, "商品类型为空");
            }
            goodsType.setDisable(Boolean.TRUE);
            goodsType = iGoodsService.saveGoodsType(goodsType);
            return getResult(goodsType.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return getResultError(ResponseCode.Common_Error, e.toString());
        }
    }
}